import {ChangeDetectorRef, Component, ElementRef} from '@angular/core';
import {AlertController, App, IonicPage, LoadingController, NavController, Platform, Loading} from 'ionic-angular';
import {Contacts, ContactFindOptions, ContactFieldType} from "@ionic-native/contacts";
import $ from "jquery";

import {ClientListProvider} from "../../../providers/client/client-list/client-list.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {ClientProspectiveProvider} from "../../../providers/client/client-prospective/client-prospective.provider";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {ClientIndividualProvider} from "../../../providers/client/client-individual/client-individual.provider";
import {LinkmanType, PhoneLinkMan} from "../../../model/pages/client/client-list/contact-item";
import {JqScrollStopService} from "../../../services/common/jq-scroll-stop.service";
import {ToastService} from "../../../services/common/toast.service";
import {ClientImportContactsProvider} from "../../../providers/client/client-import-contacts/client-import-contacts.provider";
import * as _ from "lodash";
import {PermissionsService} from "../../../services/native/permissions/permissions.service";

@IonicPage()
@Component({
    selector: 'page-client-import-contacts',
    templateUrl: 'client-import-contacts.html',
    providers: [
        Contacts,
        ClientListProvider,
        ClientImportContactsProvider,
        ClientIndividualProvider,
        ClientProspectiveProvider,
        MessageBushService,
        JqScrollStopService,
        TabsPage,
        SideMenuService,
        PermissionsService,
        ToastService
    ]
})

export class ClientImportContactsPage {
    contactList: PhoneLinkMan[] = [];
    searchKeyword: string;
    alphas: { v: string, isCurrent: boolean }[];
    content;
    dataScrollingStore: any = {};
    indexItem: any;
    groupEleHeight = this.cProvider.vw(8.33);
    contactEleHeight = this.cProvider.vw(12.96);
    scrollContent;
    isContentScrolling: boolean;
    scrollContentStyle = {};
    scrollContentSourceEle;
    scrollContentHeight;
    indexWrapperOffset: any;
    indexItemHeight: any;
    totalHeight: number;
    //偏移量
    offsetTopSingle = 0;//-this.cProvider.vw(0.5);
    alphaOffset = 0;
    tailPaddingBottom = 0;
    currentPageContact: {
        list: PhoneLinkMan[]
    };


    allSearchContacts = [];  //未排序供搜索的数组
    isCheckedAll: boolean = false;//是否全选
    checkedContactsTotal: number = 0; //已选联系人总数
    loading: Loading;
    checkTitle: string = '全选';
    specialRegex: RegExp = /^[a-zA-Z\u4e00-\u9fa5\·\ \s]$/;// /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/img;

    isViewDidLoad = false;
    isLoaded: boolean = false;

    constructor(public tabsPage: TabsPage,
                public contacts: Contacts,
                public navCtrl: NavController,
                public alertCtrl: AlertController,
                public cProvider: ClientListProvider,
                public clientImportProvider: ClientImportContactsProvider,
                public loadCtr: LoadingController,
                public _elementRef: ElementRef,
                public scrollStopsService: JqScrollStopService,
                public changeRef: ChangeDetectorRef,
                public platform: Platform,
                public toastService: ToastService,
                private permissionsService: PermissionsService,
                public app: App) {
        this.currentPageContact = {
            list: []
        };
    }

    ionViewDidLoad() {
        this.scrollStopsService.init();
        this.isViewDidLoad = true;
        this.alphas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('').map(al => {
            return {
                v: al,
                isCurrent: false
            }
        });
        this.elementInit();
    }

    ionViewDidEnter() {
        this.isViewDidLoad = false;
    }

    elementInit() {
        this.content = $('page-client-import-contacts .content');
        setTimeout(() => {
            this.indexItem = $('page-client-import-contacts .contact-list-item');
            this.scrollContentSourceEle = $('page-client-import-contacts .scroll-content');
            this.indexWrapperOffset = $('page-client-import-contacts .contact-list-index').find('.button-inner').offset();
            let h = this.indexItem.height();
            this.indexItemHeight = Math.floor(h);
            this.scrollContent = $('page-client-import-contacts .contact-wrapper');
            this.scrollContentHeight = this.scrollContent.height();
            this.getPhoneContactData();
            this.setIndexEventHandle();
        }, 500);
    }

    onSuccess(contacts) {
        let contactsLength = contacts.length;
        this.allSearchContacts = [];//每次都清空
        //显示的名称，Android ios不同
        let isAndroid = true;
        if (this.platform.is('ios')) {
            isAndroid = false;
        }

        for (let i = 0; i < contactsLength; i++) {
            let contactInstance = contacts[i]._objectInstance;
            if (contactInstance.phoneNumbers == null) {
                //没有电话的联系人不导入通讯录
                continue;
            }
            let obj = {
                id: '',
                name: '',
                phone: '',
            };

            if (isAndroid) {
                if (contactInstance.displayName != null) {
                    obj.name = contactInstance.displayName;
                } else if (contactInstance.name != null && contactInstance.name.formatted != null) {
                    obj.name = contactInstance.name.formatted;
                }
            } else {
                //ios 取一个不为空的name
                if (contactInstance.name != null && contactInstance.name.formatted != null) {
                    obj.name = contactInstance.name.formatted;
                }
            }
            obj.id = contactInstance.id;
            let phoneArray = contactInstance.phoneNumbers;
            if (phoneArray) {
                phoneArray.forEach((item) => {
                    obj.phone += this.convertPhone(item.value) + ';';
                });
            }

            this.allSearchContacts.push(obj);
            obj = null;
        }

        let keyWord = this.searchKeyword;
        let filterContacts = [];
        if (keyWord) {
            this.allSearchContacts.forEach((item) => {
                if (item.name.indexOf(keyWord) > -1 || item.phone.indexOf(keyWord) > -1) {
                    filterContacts.push(item);
                }
            });
            this.allSearchContacts = filterContacts;
        }

        //按首字母顺序格式化后的数组
        let formatContactsList = this.cProvider.importPhoneGroupingFlat(this.allSearchContacts);

        this.contactList = formatContactsList.map(item => {
            const data = new PhoneLinkMan();
            data.title = item.name || item.groupName;
            data.itemType = item.groupName ? LinkmanType.Group : LinkmanType.Client;
            data.total = item.total;
            data.checked = false;
            data.phone = item.phone;
            return data;
        });
        this.dataRender(this.contactList);
    }


    /**
     * 获取数据
     */
    getPhoneContactData(isSearch?) {
        /*let temp = [
             {
                 name: '李四*#&',
                 phone: '13890758896'
             },
             {
                 name: '',
                 phone: '13890758897'
             },
             {
                 name: '李三三1',
                 phone: '45555555'
             },
             {
                 name: 'Kevin111111111111112345678',
                 phone: '15890758895'
             },
             {
                 name: '刘德华',
                 phone: '138907511115'
             },
             {
                 name: '张三',
                 phone: '138907521222'
             },

             {
                 name: 'jack',
                 phone: '138907561666'
             },
             {
                 name: '步景云',
                 phone: '0828698981898'
             },
             {
                 name: '千秋',
                 phone: '138907156666'
             },
             {
                 name: '',
                 phone: '138907581897'
             },
             {
                 name: 'ca',
                 phone: '138307581811'
             },
             {
                 name: '李四',
                 phone: '158907518899'
             },
             {
                 name: '刘德华',
                 phone: '138907511111'
             },
             {
                 name: '张三',
                 phone: '138907521222'
             },

             {
                 name: 'jack',
                 phone: '13890766626'
             },
             {
                 name: 'cindy',
                 phone: '13890756666'
             },
             {
                 name: '千秋',
                 phone: '138907569666'
             },
             {
                 name: '哎中*#&',
                 phone: '13890597'
             },
             {
                 name: '李三三',
                 phone: '138308811'
             },
             {
                 name: '李四',
                 phone: '1589075899'
             },
             {
                 name: '刘德华',
                 phone: '138905111'
             },
             {
                 name: 'Cindy',
                 phone: '13890752'
             },

             {
                 name: 'jack',
                 phone: '138905666'
             },
             {
                 name: '步景云',
                 phone: '138905666'
             },
             {
                 name: '千秋',
                 phone: '1389075666'
             },
             {
                 name: '哎中',
                 phone: '13808897'
             },
             {
                 name: '李三三',
                 phone: '1330751'
             },
             {
                 name: '李四',
                 phone: '1589075899'
             },
             {
                 name: '刘德华',
                 phone: '1389051511'
             },
             {
                 name: '张三121212',
                 phone: '1390752222'
             },

             {
                 name: 'jack',
                 phone: '138915666'
             },
             {
                 name: '步景云',
                 phone: '1319075666'
             },
             {
                 name: '千秋',
                 phone: '1381075666'
             }
         ];

         let keyWord = this.searchKeyword;
         var t = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
         let filterContacts = [];
         if (keyWord) {
             this.allSearchContacts.forEach((item) => {
                 if (item.name.indexOf(keyWord) > -1 || item.phone.indexOf(keyWord) > -1) {

                     filterContacts.push(item);
                 }
             });
             this.allSearchContacts = filterContacts;
         }

         for (var i = 0; i < 59; i++) {
             for (var j = 0; j < temp.length; j++) {
                 let item= _.clone(temp[j]);
                 let rand=Math.floor(Math.random() * 10 + 1);

                 item.phone = item.phone + t[rand-1]+';';
                 let rand2=Math.floor(Math.random() * 10 + 1);
                 item.name=item.name+t[rand2-1];
                 this.allSearchContacts.push(item);
             }
         }

         let contactItemList = this.cProvider.importPhoneGroupingFlat(this.allSearchContacts);

         this.contactList = contactItemList.map(item => {
             const data = new PhoneLinkMan();
             data.title = item.name || item.groupName;
             data.itemType = item.groupName ? LinkmanType.Group : LinkmanType.Client;
             data.avatar = this.cProvider.getClientAvatar(data);
             data.total = item.total;
             data.phone = item.phone;
             return data;
         });
         this.dataRender(this.contactList);*/

        if (this.platform.is('android')) {

        }
        else {
            //
        }

        this.permissionsService.checkContactPermission().then(res => {
            if (res) {
                console.log(res);
                this.isLoaded = false;
                this.checkedContactsTotal = 0;//清空
                let options = new ContactFindOptions();
                let fields: ContactFieldType[];
                fields = ['id', 'displayName', 'phoneNumbers', 'categories', 'organizations'];
                options.filter = "";
                options.multiple = true;
                options.hasPhoneNumber = true;
                if (isSearch) {
                    this.showLoading('加载中');
                } else {
                    this.showLoading('正在获取手机通讯录');
                }

                this.contacts.find(fields, options).then((result) => {
                    this.onSuccess(result);
                    this.dismissLoading();
                    this.isLoaded = true;
                }, (error) => {
                    console.log(error);
                    this.dismissLoading();
                    this.isLoaded = true;
                });
            } else {
                this.permissionsService.getContactsPermission().then(res => {
                    if (res != 'authorized') {
                        this.toastService.showToast('请到“设置>隐私”启用“通讯录”',2000);
                    }
                }).catch(() => {
                    this.toastService.showToast('请到“设置>隐私”启用“通讯录”',2000);
                });
            }
        })

    }

    //region 数据渲染
    getHeightByIndex(start: number, last: number) {
        let totalHeight = 0;
        for (let i = start; i < last; i++) {
            let item = this.contactList[i];
            let itemHeight = 0;
            if (item.itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight - this.offsetTopSingle;
            } else {
                itemHeight = this.contactEleHeight - this.offsetTopSingle;
            }
            totalHeight += itemHeight;
        }
        return totalHeight;
    }

    getContactListByIndex(index, startTop) {
        let currentList = [];
        let pHeight = startTop;
        let singleGreenHeight = 0;
        let i = index;
        for (let len = this.contactList.length; i < len; i++) {
            this.contactList[i].style = {};
            let itemHeight = 0;
            if (this.contactList[i].itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight;
            } else {
                itemHeight = this.contactEleHeight;
            }
            this.contactList[i].style.top = (pHeight + singleGreenHeight) + 'px';
            singleGreenHeight += itemHeight;
            currentList.push(this.contactList[i]);
            if (singleGreenHeight >= this.scrollContentHeight) break;
        }
        return {i: i + 1, list: currentList, lastTop: pHeight + singleGreenHeight};
    }

    getContactListByScreen(index): PhoneLinkMan[] {

        //region 计算上一页样式与数据
        let startGreenHeight = 0;
        const prevList: PhoneLinkMan[] = [];
        let prevStart = -1;
        if (index > 0) {
            let start = index - 1;
            let singleGreenHeight = 0;
            for (let i = start; i > -1; i--) {
                let itemData = this.contactList[i];
                itemData.style = {};
                let itemHeight = 0;
                if (this.contactList[i].itemType === LinkmanType.Group) {
                    itemHeight = this.groupEleHeight;
                } else {
                    itemHeight = this.contactEleHeight;
                }
                singleGreenHeight += itemHeight;
                prevList.push(itemData);
                if (singleGreenHeight >= this.scrollContentHeight) {
                    prevStart = i;
                    break;
                }
            }
        }
        if (prevStart > 0) {
            startGreenHeight = this.getHeightByIndex(0, prevStart);
        }
        prevList.reverse();
        let prevSingHeight = 0;
        prevList.forEach(item => {
            item.style.top = (startGreenHeight + prevSingHeight) + 'px';
            let itemHeight = 0;
            if (item.itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight - this.offsetTopSingle;
            } else {
                itemHeight = this.contactEleHeight - this.offsetTopSingle;
            }
            prevSingHeight += itemHeight;
        });
        //endregion

        let startTop = startGreenHeight + prevSingHeight;
        let current = this.getContactListByIndex(index, startTop);
        let nextData = this.getContactListByIndex(current.i, current.lastTop);

        return prevList.concat(current.list).concat(nextData.list);
    }

    dataTotal = 0;

    dataRender(clientList: PhoneLinkMan[]) {
        if (!this.totalHeight || this.dataTotal != clientList.length) {
            let totalHeight = 0;
            this.contactList.forEach(i => {
                if (i.itemType === LinkmanType.Group) {
                    totalHeight += (this.groupEleHeight - this.offsetTopSingle);
                } else {
                    totalHeight += (this.contactEleHeight - this.offsetTopSingle);
                }
            });
            this.totalHeight = totalHeight + this.tailPaddingBottom;
        }

        this.currentPageContact.list = this.getContactListByScreen(0);
        this.dataTotal = clientList.length;
        this.scrollContent.scrollTop(0);
    }

    //region 搜索关键字
    inputKeyUp(e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            this.searchHandle();
        }
    }

    //搜索按钮点击搜索通讯录
    searchHandle() {
        this.getPhoneContactData(true);
    }

    //endregion

    //region 字母索引
    contentScrollStopped() {
        this.isContentScrolling = false;
    }

    setContentScrollingTimer = null;

    setContentScrolling() {

        const handler = () => {
            if (this.setContentScrollingTimer) {
                clearTimeout(this.setContentScrollingTimer);
            }
            this.setContentScrollingTimer = setTimeout(() => {
                this.setContentScrollingTimer = null;
                this.contentScrollStopped();
            }, 100);

            this.isContentScrolling = true;
            if (!this.dataScrollingStore.isAlphaIndexTouch) {
                const scrollTop = this.scrollContent.scrollTop();
                let groupItem: PhoneLinkMan;
                let foundIndex = 0;
                let totalTop = 0;
                for (let i = 0, max = this.contactList.length; i < max; i++) {
                    const itemTemp = this.contactList[i];
                    if (itemTemp.itemType === LinkmanType.Group) {
                        groupItem = itemTemp;
                        totalTop += (this.groupEleHeight - this.offsetTopSingle);
                    } else {
                        totalTop += (this.contactEleHeight - this.offsetTopSingle);
                    }
                    if (totalTop >= scrollTop + this.tailPaddingBottom) {
                        foundIndex = i;
                        break;
                    }
                }
                if (groupItem) {
                    this.setIndexStyleByAlpha(groupItem.title);
                    this.currentPageContact.list = this.getContactListByScreen(foundIndex);
                }

            }
        };
        this.scrollContent.bind('scroll', handler).data('eee', handler);
    }

    setIndexStyleByAlpha(alpha) {
        if (!alpha) {
            alpha = this.alphas[0].v;
        }
        this.alphas.forEach((al, i) => {
            if (al.v === alpha) {
                this.alphas['selected'] = i;
                this.dataScrollingStore.preIndex = i;
            }
            al.isCurrent = al.v === alpha;
        });
    }


    movingSetIndexPrames = [];
    setCurrentAlphaTimout;

    queueSetScreenClient() {
        if (this.movingSetIndexPrames.length) {
            const p = this.movingSetIndexPrames[0];
            this.setScreenClientList.apply(this, p);
            this.movingSetIndexPrames.shift();
        }
        this.setCurrentAlphaTimout = setTimeout(() => {
            this.queueSetScreenClient();
        }, 100);
    }

    setLastScreenClient() {
        let param = this.movingSetIndexPrames[this.movingSetIndexPrames.length - 1];
        if (param) {
            this.setScreenClientList.apply(this, param);
        }
    }

    /**
     * 手势上下滑动客户列表
     */
    setIndexEventHandle() {

        this.setCurrentIndex(0);

        this.content.unbind('touchstart').bind('touchstart', e => {
            e.stopPropagation();
            let event = e;
            if (e.originalEvent) {
                event = e.originalEvent;
            }
            if (event.targetTouches && event.targetTouches.length === 1) {
                let touchX = event.touches[0].clientX;
                let touchY = event.touches[0].clientY;
                touchY += (touchY * this.alphaOffset);

                //手势触摸横向大于91.94时
                if (touchX > this.cProvider.vw(91.94) && !this.isContentScrolling) {
                    const deltaY = touchY - this.indexWrapperOffset.top;
                    let alphaIndex = -1;
                    if (deltaY <= 0) {
                        alphaIndex = 0;
                    } else {
                        alphaIndex = Math.round(deltaY / this.indexItemHeight);
                        // alphaIndex = Math.floor(deltaY / this.indexItemHeight);
                    }
                    this.dataScrollingStore.isAlphaIndexTouch = true;
                    if (this.dataScrollingStore.preIndex !== alphaIndex && alphaIndex > -1) {
                        this.setCurrentIndex(alphaIndex);
                        this.setScreenClientList(alphaIndex, this.groupEleHeight, this.contactEleHeight, this.scrollContent);
                        this.dataScrollingStore.preIndex = alphaIndex;
                    }
                } else {
                    this.setContentScrolling();
                }
            }
        });
        this.content.unbind('touchmove').bind('touchmove', e => {
            e.stopPropagation();
            let event = e;
            if (e.originalEvent) {
                event = e.originalEvent;
            }
            if (this.dataScrollingStore.isAlphaIndexTouch) {
                let touchY = event.touches[0].clientY;
                touchY += (touchY * this.alphaOffset);
                const deltaY = touchY - this.indexWrapperOffset.top;
                let alphaIndex = -1;
                if (deltaY <= 0) {
                    alphaIndex = 0;
                } else {
                    alphaIndex = Math.floor(deltaY / this.indexItemHeight);
                }
                if (this.dataScrollingStore.preIndex !== alphaIndex && alphaIndex > -1) {
                    this.setCurrentIndex(alphaIndex);
                    this.movingSetIndexPrames.push([
                        alphaIndex,
                        this.groupEleHeight,
                        this.contactEleHeight,
                        this.scrollContent
                    ]);
                    this.setScreenClientList(alphaIndex, this.groupEleHeight, this.contactEleHeight, this.scrollContent);
                    this.dataScrollingStore.preIndex = alphaIndex;
                }
            }
        });
        this.content.unbind('touchend').bind('touchend', () => {
            this.dataScrollingStore.isAlphaIndexTouch = false;
            this.setLastScreenClient();
            this.movingSetIndexPrames = [];
            if (this.setCurrentAlphaTimout) clearTimeout(this.setCurrentAlphaTimout);
        });

    }

    getContactByLetter(letter: string) {
        for (let i = 0, len = this.contactList.length; i < len; i++) {
            const item = this.contactList[i];
            if (item.title === letter) {
                this.currentPageContact.list = this.getContactListByScreen(i);
                try {
                    this.changeRef.detectChanges();
                } catch (e) {
                }
                break;
            }
        }
    }

    setCurrentIndex(index: number) {
        if (this.scrollContent)
            this.scrollContent.unbind('scroll');

        //参数检查
        if (index < 1) index = 0;
        if (index > this.alphas.length - 1) {
            index = this.alphas.length - 1;
        }

        let currentLetter = this.alphas[index];
        // 设置字母索引列表选中项样式
        const selectedIndex = this.alphas['selected'];
        if (selectedIndex > -1) {
            this.alphas[selectedIndex].isCurrent = false;
        }
        currentLetter.isCurrent = true;
        this.alphas['selected'] = index;
    }

    setScreenClientList(index: number, groupHeight?: number, clientHeight?: number, content?: any) {
        if (!groupHeight || !clientHeight || !content) return;

        //参数检查
        if (index < 1) index = 0;
        if (index > this.alphas.length - 1) {
            index = this.alphas.length - 1;
        }
        let groups = this.contactList.filter(item => item.itemType === LinkmanType.Group);
        // 设置滚动列表位置
        let scrollTopHeight = 0;
        let contactGroupLocationAlpha;
        let detectiveLetter = this.alphas[0].v;
        // 查找不为空的分组以计算分组高度
        const foundNoneAlpha = (detectIndex) => {
            if (detectIndex < 1) return [];
            const setAlpha = this.alphas[detectIndex];

            let f = -1;
            for (let indexIn = 0; indexIn < groups.length; indexIn++) {
                if (groups[indexIn].title === setAlpha.v) {
                    contactGroupLocationAlpha = setAlpha.v;
                    f = indexIn;
                    detectiveLetter = setAlpha.v;
                    break;
                }
            }
            if (f > -1) {
                return groups.slice(0, f);
            } else {
                return foundNoneAlpha(detectIndex - 1);
            }
        };
        groups = foundNoneAlpha(index);
        groups.forEach(g => {
            if (g.total) {
                scrollTopHeight += groupHeight;
                // scrollTopHeight += (g.total * clientHeight);
                scrollTopHeight += (g.total * (clientHeight - 0.05));
            }
        });

        this.getContactByLetter.call(this, detectiveLetter);

        content.stop(true, true);
        content.animate({
                scrollTop: `${scrollTopHeight}px`
            },
            100,
            void 0);
    }

    /**
     * 后退
     */
    backHandle() {
        this.navCtrl.pop();
    }

    /**
     * 显示加载提示
     * @param tipMsg 提示信息
     */
    showLoading(tipMsg) {
        this.loading = this.loadCtr.create({
            spinner: 'circles',
            content: tipMsg //""
        });
        this.loading.present();
    }

    /**
     * 关闭加载提示
     */
    dismissLoading() {
        if (this.loading) {
            this.loading.dismiss();
        }
    }

    /**
     * 完成导入数据
     */
    finishImport() {

        let importManList = [],
            emptyNameList = [],
            realImportName = [];
        this.contactList.forEach((item) => {
            if (!(item.checked && item.itemType == LinkmanType.Client)) {
                return;
            }
            let importContact = {
                name: '',
                mobileList: []
            };

            let name = item.title || '';
            if (name.length > 20) {
                //20个字超长则截取
                name = name.substr(0, 19);
            }
            /* name = name.replace(this.specialRegex, '.');*/
            //性能不太好，需优化
            let nameList = name.split('');
            /* nameList.forEach((item) => {
                 if (!this.specialRegex.test(item)) {
                     name = name.replace(item, '·');
                 }
             })*/

            importContact['name'] = name;
            let phoneStr = item.phone,
                lastIndex = phoneStr.lastIndexOf(';'),
                phoneList = phoneStr.substr(0, lastIndex).split(';');
            phoneList.forEach((phone) => {
                importContact.mobileList.push({
                    'mobile': phone
                })

            });
            importManList.push(importContact);

            if (item.title) {
                //名字存在 才导入数据库
                realImportName.push(importContact);
            } else {
                emptyNameList.push(importContact);
            }
        });

        if (importManList.length === 0) {
            this.toastService.showToast(`请至少选择1位客户`, 2000);
            return;
        }

        //姓名为空的人
        if (emptyNameList.length === importManList.length) {
            this.toastService.showToast(`成功添加0位客户`, 2000);
            return;
        }

        this.showLoading('正在导入手机通讯录');
        console.info(realImportName);
        this.clientImportProvider.importPhone(realImportName).subscribe((res) => {
            this.dismissLoading();
            let tipMsg = `成功添加${res.success}位客户`;
            if (res.repeat != 0) {
                tipMsg += `,有${res.repeat}位客户信息重复`;
            }
            this.toastService.showToast(tipMsg, 2000);
            MessageBushService.setMessage(MessageBushService.keys.clientListUpdated, '1');
            setTimeout(() => {
                this.navCtrl.pop();
            }, 1600);

        }, (error) => {
            this.toastService.showToast('导入通讯录失败', 2000);
            this.dismissLoading();
        });
    }

    /**
     * 将不同手机电话转换成相同格式 138-1900-1211/138 1900 1211  ==> 13819001211
     * @param {string} phoneNumber
     * @returns {T}
     */
    convertPhone(phoneNumber: string) {
        if (!phoneNumber) {
            return;
        }
        let regex = /\d+/g;
        let matchPhones = phoneNumber.match(regex);

        return matchPhones.reduce((prev, current) => {
            return prev + current;
        });
    }

    /**全选*/
    checkAll() {
        this.isCheckedAll = !this.isCheckedAll;
        if (this.isCheckedAll) {
            this.checkedContactsTotal = this.allSearchContacts.length;
            this.checkTitle = '全不选';
        } else {
            this.checkedContactsTotal = 0;
            this.checkTitle = '全选';
        }
        this.contactList.forEach((item) => {
            item.checked = this.isCheckedAll;
        });
    }

    /**
     * 单个按钮 复选事件
     * @param item
     */
    checkedChange(item) {
        if (item.checked) {
            this.checkedContactsTotal++;
        } else {
            this.checkedContactsTotal--;
        }
    }

}
